package com.kelvin.backend.common.web.controller;

import cn.hutool.core.util.ObjectUtil;
import com.kelvin.backend.common.log.WebLog;
import com.kelvin.backend.common.web.entity.BaseEntity;
import com.kelvin.backend.common.web.response.BaseResponse;
import com.kelvin.backend.common.web.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;

/**
 * <p>Title: BaseController</p>
 * <p>Description: </p>
 *
 * @author Kelvin.Chen
 * @datetime 2021/7/8 15:53
 */
public class BaseController<S extends BaseService, T extends BaseEntity> {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    protected S baseService;

    /**
     * 判断上传的文件是否不为空
     * true不为空，false为空
     *
     * @param file
     * @return
     */
    protected boolean isFileNotEmpty(MultipartFile file) {
        return null != file && !file.isEmpty();
    }

    /**
     * 验证参数完整性
     *
     * @param obj 不定参数，可以传入多个值
     * @return 参数完整返回 true 不完整返回false
     */
    protected boolean validate(Object... obj) {
        boolean validate = true;
        for (int i = 0; i < obj.length; i++) {
            if (ObjectUtil.isEmpty(obj[i])) {
                validate = false;
                break;
            }
        }
        return validate;
    }

    /**
     * 根据ID获取
     *
     * @param id
     * @return
     */
    @WebLog(description = "根据ID获取")
    @GetMapping("/get/{id}")
    public BaseResponse<T> get(@PathVariable Serializable id) {
        T entity = (T) baseService.selectById(id);
        if (null != entity) {
            return BaseResponse.success(entity);
        } else {
            return BaseResponse.fail("未找到相关信息");
        }
    }

    /**
     * 更新或保存数据（更新需要传ID）
     *
     * @param entity
     * @return
     */
    @WebLog(description = "更新或保存数据")
    @PostMapping("/save")
    public BaseResponse save(@RequestBody T entity) {
        return baseService.saveOrUpdate(entity) ? BaseResponse.success() : BaseResponse.fail("");
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @WebLog(description = "根据ID删除")
    @GetMapping("/delete/{id}")
    public BaseResponse delete(@PathVariable Serializable id) {
        T exists = (T) baseService.selectById(id);
        if (null == exists) {
            return BaseResponse.fail("未找到该信息");
        }
        return baseService.deleteById(id) ? BaseResponse.success() : BaseResponse.fail("");
    }
}
